{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Title: #Pattern Matching LCCI"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Difficulty: #Medium"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Category Title: #LCCI"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Tag Slug: #math #string #backtracking #enumeration"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Name Translated: #数学 #字符串 #回溯 #枚举"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Solution Name: patternMatching"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Translated Title: #模式匹配"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Translated Content:\n",
    "<p>你有两个字符串，即<code>pattern</code>和<code>value</code>。 <code>pattern</code>字符串由字母<code>&quot;a&quot;</code>和<code>&quot;b&quot;</code>组成，用于描述字符串中的模式。例如，字符串<code>&quot;catcatgocatgo&quot;</code>匹配模式<code>&quot;aabab&quot;</code>（其中<code>&quot;cat&quot;</code>是<code>&quot;a&quot;</code>，<code>&quot;go&quot;</code>是<code>&quot;b&quot;</code>），该字符串也匹配像<code>&quot;a&quot;</code>、<code>&quot;ab&quot;</code>和<code>&quot;b&quot;</code>这样的模式。但需注意<code>&quot;a&quot;</code>和<code>&quot;b&quot;</code>不能同时表示相同的字符串。编写一个方法判断<code>value</code>字符串是否匹配<code>pattern</code>字符串。</p>\n",
    "\n",
    "<p><strong>示例 1：</strong></p>\n",
    "\n",
    "<pre><strong>输入：</strong> pattern = &quot;abba&quot;, value = &quot;dogcatcatdog&quot;\n",
    "<strong>输出：</strong> true\n",
    "</pre>\n",
    "\n",
    "<p><strong>示例 2：</strong></p>\n",
    "\n",
    "<pre><strong>输入：</strong> pattern = &quot;abba&quot;, value = &quot;dogcatcatfish&quot;\n",
    "<strong>输出：</strong> false\n",
    "</pre>\n",
    "\n",
    "<p><strong>示例 3：</strong></p>\n",
    "\n",
    "<pre><strong>输入：</strong> pattern = &quot;aaaa&quot;, value = &quot;dogcatcatdog&quot;\n",
    "<strong>输出：</strong> false\n",
    "</pre>\n",
    "\n",
    "<p><strong>示例 4：</strong></p>\n",
    "\n",
    "<pre><strong>输入：</strong> pattern = &quot;abba&quot;, value = &quot;dogdogdogdog&quot;\n",
    "<strong>输出：</strong> true\n",
    "<strong>解释：</strong> &quot;a&quot;=&quot;dogdog&quot;,b=&quot;&quot;，反之也符合规则\n",
    "</pre>\n",
    "\n",
    "<p><strong>提示：</strong></p>\n",
    "\n",
    "<ul>\n",
    "\t<li><code>1 &lt;= len(pattern) &lt;= 1000</code></li>\n",
    "\t<li><code>0 &lt;= len(value) &lt;= 1000</code></li>\n",
    "\t<li>你可以假设<code>pattern</code>只包含字母<code>&quot;a&quot;</code>和<code>&quot;b&quot;</code>，<code>value</code>仅包含小写字母。</li>\n",
    "</ul>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Description: [pattern-matching-lcci](https://leetcode.cn/problems/pattern-matching-lcci/description/)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Solutions: [pattern-matching-lcci](https://leetcode.cn/problems/pattern-matching-lcci/solutions/)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test_cases = ['\"abba\"\\n\"dogcatcatdog\"', '\"abba\"\\n\"dogcatcatfish\"', '\"aaaa\"\\n\"dogcatcatdog\"', '\"abba\"\\n\"dogdogdogdog\"']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        # if not pattern:return not value\n",
    "        # if len(pattern)==1:return True\n",
    "        # a,b = ('\\\\1','\\\\2') if pattern[0]=='a' else ('\\\\2','\\\\1')\n",
    "        # p = pattern.replace('a','(\\\\w*)',1).replace('b','(\\\\w*)',1).replace('a',a).replace('b',b)\n",
    "        # res = re.match('^'+p+'$',value)\n",
    "        # return bool(res and (len(res.groups())==1 or res.groups()[0]!=res.groups()[1]))\n",
    "\n",
    "\n",
    "        n = len(value)\n",
    "        ma,mb = pattern.count('a'),pattern.count('b')\n",
    "        if n==0:\n",
    "            if ma*mb==0:return True\n",
    "            else:return False\n",
    "        if ma==1 or mb==1:return True\n",
    "        if ma==0 and mb==0:return False\n",
    "        if ma<mb:\n",
    "            pattern = pattern.replace('a','c').replace('b','a').replace('c','b')\n",
    "            ma,mb = mb,ma\n",
    "        for x in range(n//ma+1):\n",
    "            dicts = {}\n",
    "            if mb!=0:\n",
    "                y = (n-ma*x)/mb\n",
    "                if y!=int(y):continue\n",
    "                else:y=int(y)\n",
    "            sta = 0\n",
    "            for i in range(ma+mb):\n",
    "                if pattern[i]=='a':\n",
    "                    dicts[pattern[i]] = value[sta:sta+x]\n",
    "                    sta += x\n",
    "                else:\n",
    "                    dicts[pattern[i]] = value[sta:sta+y]\n",
    "                    sta+=y\n",
    "                if mb==0 or len(dicts)==2:break\n",
    "            if mb!=0 and dicts['a']==dicts['b']:continue\n",
    "            acc = ''\n",
    "            for c in pattern:\n",
    "                acc+=dicts[c]\n",
    "            if acc==value:\n",
    "                return True\n",
    "        return False\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        if not pattern:return not value\n",
    "        if len(pattern)==1:return True\n",
    "        a,b = ('\\\\1','\\\\2') if pattern[0]=='a' else ('\\\\2','\\\\1')\n",
    "        p = pattern.replace('a','(\\\\w*)',1).replace('b','(\\\\w*)',1).replace('a',a).replace('b',b)\n",
    "        res = re.match('^'+p+'$',value)\n",
    "        return bool(res and (len(res.groups())==1 or res.groups()[0]!=res.groups()[1]))\n",
    "\n",
    "\n",
    "        # n = len(value)\n",
    "        # ma,mb = pattern.count('a'),pattern.count('b')\n",
    "        # if n==0:\n",
    "        #     if ma*mb==0:return True\n",
    "        #     else:return False\n",
    "        # if ma==1 or mb==1:return True\n",
    "        # if ma==0 and mb==0:return False\n",
    "        # if ma<mb:\n",
    "        #     pattern = pattern.replace('a','c').replace('b','a').replace('c','b')\n",
    "        #     ma,mb = mb,ma\n",
    "        # for x in range(n//ma+1):\n",
    "        #     dicts = {}\n",
    "        #     if mb!=0:\n",
    "        #         y = (n-ma*x)/mb\n",
    "        #         if y!=int(y):continue\n",
    "        #         else:y=int(y)\n",
    "        #     sta = 0\n",
    "        #     for i in range(ma+mb):\n",
    "        #         if pattern[i]=='a':\n",
    "        #             dicts[pattern[i]] = value[sta:sta+x]\n",
    "        #             sta += x\n",
    "        #         else:\n",
    "        #             dicts[pattern[i]] = value[sta:sta+y]\n",
    "        #             sta+=y\n",
    "        #         if mb==0 or len(dicts)==2:break\n",
    "        #     if mb!=0 and dicts['a']==dicts['b']:continue\n",
    "        #     acc = ''\n",
    "        #     for c in pattern:\n",
    "        #         acc+=dicts[c]\n",
    "        #     if acc==value:\n",
    "        #         return True\n",
    "        # return False\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        # 边界情况处理\n",
    "        if not pattern: return not value\n",
    "        if len(pattern) == 1: return True\n",
    "\n",
    "        # 构造正则表达式：重点是正则表达式的“后向引用”\n",
    "        rega, regb = ('\\\\1', '\\\\2') if pattern[0] == 'a' else ('\\\\2', '\\\\1')\n",
    "        p = pattern.replace('a', '(\\\\w*)', 1).replace('b', '(\\\\w*)', 1).replace('a', rega).replace('b', regb)\n",
    "        p = '^' + p + '$'\n",
    "        m = re.match(p, value)\n",
    "\n",
    "        # 匹配到 && (模式长度为1 || 模式长度为2 && 两个模式不相同)\n",
    "        return bool(m and (len(m.groups()) == 1 or m.groups()[0] != m.groups()[1]))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        if pattern[0]=='b':\n",
    "            pattern = pattern.replace('a', 'c').replace('b', 'a').replace('c', 'b')\n",
    "        xa, xb = pattern.count('a'), pattern.count('b')\n",
    "        if xb == 0:\n",
    "            a = value[:len(value)//xa]\n",
    "            return a*xa == value\n",
    "        for i in range(len(value)+1):\n",
    "            if (len(value)-xa*i)%xb==0:\n",
    "                a, b, s = value[:i], None, ''\n",
    "                for alpha in pattern:\n",
    "                    if alpha == 'a': s += a\n",
    "                    else:\n",
    "                        if b == None: b = value[len(s):len(s)+(len(value)-xa*i)//xb]\n",
    "                        s += b\n",
    "                if s == value and a!=b: return True\n",
    "        return False\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        a_count = pattern.count(\"a\") if \"a\" in pattern else 0\n",
    "        b_count = len(pattern) - a_count\n",
    "        n = len(value)\n",
    "\n",
    "        if a_count == 0 or b_count == 0:\n",
    "            x_count = a_count + b_count\n",
    "            x_len = n//x_count\n",
    "            x = value[:x_len]\n",
    "            return x_count * x == value\n",
    "\n",
    "        x, x_count, y, y_count = ('a', a_count, 'b', b_count) if pattern.startswith('a') else ('b', b_count, 'a', a_count)\n",
    "        y_begin_ind = pattern.find(y)\n",
    "        p2str = {}\n",
    "        for x_len in range(0, n//x_count+1):\n",
    "            y_len = (n - x_len*x_count) // y_count\n",
    "            if (x_len * x_count + y_len * y_count) == n:\n",
    "                p2str[x] = value[:x_len]\n",
    "                p2str[y] = value[y_begin_ind*x_len:(y_begin_ind*x_len+y_len)]\n",
    "                value_pattern = \"\".join([p2str[p] for p in pattern])\n",
    "                if p2str[x] != p2str[y] and value_pattern == value:\n",
    "                    return True\n",
    "        return False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        count_a=sum(1 for ch in pattern if ch=='a')\n",
    "        count_b=len(pattern)-count_a\n",
    "\n",
    "        if count_a<count_b:\n",
    "            count_a,count_b=count_b,count_a\n",
    "            pattern=''.join('a' if ch=='b' else 'b' for ch in pattern)\n",
    "\n",
    "        if not value:\n",
    "            return count_b==0\n",
    "        if not pattern:\n",
    "            return False \n",
    "\n",
    "        for len_a in range(len(value)//count_a+1):\n",
    "            rest=len(value)-count_a*len_a\n",
    "            if (count_b==0 and rest==0) or (count_b!=0 and rest%count_b==0):\n",
    "                len_b=0 if count_b==0 else rest//count_b\n",
    "                pos,correct=0,True\n",
    "                value_a,value_b=None,None\n",
    "                for ch in pattern:\n",
    "                    if ch=='a':\n",
    "                        sub=value[pos:pos+len_a]\n",
    "                        if not value_a:\n",
    "                            value_a=sub\n",
    "                        elif value_a!=sub:\n",
    "                            correct=False\n",
    "                            break\n",
    "                        pos+=len_a\n",
    "                    else:\n",
    "                        sub=value[pos:pos+len_b]\n",
    "                        if not value_b:\n",
    "                            value_b=sub\n",
    "                        elif value_b!=sub:\n",
    "                            correct=False\n",
    "                            break\n",
    "                        pos+=len_b\n",
    "                if correct and value_a!=value_b:\n",
    "                    return True\n",
    "        return False\n",
    "                    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        if not pattern:\n",
    "            return not value\n",
    "        a_cnt, b_cnt = pattern.count('a'), pattern.count('b')\n",
    "        for a_l in range(1 if a_cnt == 0 else (len(value) // a_cnt + 1)):\n",
    "            lens, strs, i = [a_l, 0], [None, None], 0\n",
    "            if not b_cnt:\n",
    "                if len(value) != a_l * a_cnt:\n",
    "                    continue\n",
    "            else:\n",
    "                if (len(value) - a_cnt * a_l) % b_cnt != 0:\n",
    "                    continue\n",
    "                lens[1] = (len(value) - a_cnt * a_l) // b_cnt\n",
    "            for p in pattern:\n",
    "                if strs[ord(p) - 97] is not None and strs[ord(p) - 97] != value[i:(i + lens[ord(p) - 97])]:\n",
    "                    break\n",
    "                strs[ord(p) - 97] = value[i:(i + lens[ord(p) - 97])]\n",
    "                i += lens[ord(p) - 97]\n",
    "            else:\n",
    "                if strs[0] != strs[1]:\n",
    "                    return True\n",
    "        return False\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        import re\n",
    "        # a为\\1 b为\\2\n",
    "        rega, regb = ('\\\\1', '\\\\2') if pattern[0] == 'a' else ('\\\\2', '\\\\1')\n",
    "\n",
    "        p = pattern.replace('a', '(\\\\w*)', 1).replace('b', '(\\\\w*)', 1).replace('a', rega).replace('b', regb)\n",
    "\n",
    "        p = '^' + p + '$'\n",
    "        m = re.match(p, value)\n",
    "        \n",
    "        if not m:\n",
    "            return False\n",
    "        if len(m.groups()) == 1:\n",
    "            return True\n",
    "        if m.groups()[0]==m.groups()[1]:\n",
    "            return False\n",
    "        return True\n",
    "\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        if not pattern: return not value\n",
    "        n=len(value)\n",
    "        a_cnt,b_cnt=pattern.count('a'),pattern.count('b')\n",
    "        a_max_l= 0 if a_cnt==0 else n//a_cnt\n",
    "        for a_l in range(a_max_l+1):\n",
    "            if not b_cnt:\n",
    "                if n!=a_l*a_cnt: continue\n",
    "                b_l=0\n",
    "            else:\n",
    "                b_total_l=n-a_cnt*a_l\n",
    "                if b_total_l%b_cnt!=0: continue\n",
    "                b_l=b_total_l//b_cnt\n",
    "            a,b=None,None\n",
    "            i=0\n",
    "            for p in pattern:\n",
    "                if p=='a':\n",
    "                    s=value[i:(i+a_l)]\n",
    "                    i+=a_l\n",
    "                    if a is not None and a!=s: break\n",
    "                    a=s\n",
    "                else:\n",
    "                    s=value[i:(i+b_l)]\n",
    "                    i+=b_l\n",
    "                    if b is not None and b!=s:\n",
    "                        break\n",
    "                    b=s\n",
    "            else:\n",
    "                if a!=b:\n",
    "                    return True\n",
    "        return False\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        a_count = pattern.count(\"a\") if \"a\" in pattern else 0\n",
    "        b_count = pattern.count(\"b\") if \"b\" in pattern else 0\n",
    "        n = len(value)\n",
    "\n",
    "        if a_count == 0 or b_count == 0:\n",
    "            x_count = a_count + b_count\n",
    "            x_len = n//x_count\n",
    "            x = value[:x_len]\n",
    "            return x_count * x == value\n",
    "\n",
    "        x, x_count, y, y_count = ('a', a_count, 'b', b_count) if pattern.startswith('a') else ('b', b_count, 'a', a_count)\n",
    "        y_begin_ind = pattern.find(y)\n",
    "        p2str = {}\n",
    "        for x_len in range(0, n//x_count+1):\n",
    "            y_len = (n - x_len*x_count) // y_count\n",
    "            if (x_len * x_count + y_len * y_count) == n:\n",
    "                p2str[x] = value[:x_len]\n",
    "                p2str[y] = value[y_begin_ind*x_len:(y_begin_ind*x_len+y_len)]\n",
    "                if p2str[x] ==  p2str[y]:\n",
    "                    continue\n",
    "                value_pattern = \"\".join([p2str[p] for p in pattern])\n",
    "                if value_pattern == value:\n",
    "                    return True\n",
    "\n",
    "        return False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        # 边界情况处理\n",
    "        if not pattern: return not value\n",
    "        if len(pattern) == 1: return True\n",
    "\n",
    "        # 构造正则表达式：重点是正则表达式的“后向引用”\n",
    "        rega, regb = ('\\\\1', '\\\\2') if pattern[0] == 'a' else ('\\\\2', '\\\\1')\n",
    "        p = pattern.replace('a', '(\\w*)', 1).replace('b', '(\\w*)', 1).replace('a', rega).replace('b', regb)\n",
    "        p = '^' + p + '$'\n",
    "        m = re.match(p, value)\n",
    "\n",
    "        # 匹配到 && (模式长度为1 || 模式长度为2 && 两个模式不相同)\n",
    "        return bool(m and (len(m.groups()) == 1 or m.groups()[0] != m.groups()[1]))\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        rega,regb=('\\\\1','\\\\2') if pattern[0]=='a' else ('\\\\2','\\\\1')\n",
    "        p=pattern.replace('a','(\\\\w*)',1).replace('b','(\\\\w*)',1).replace('a',rega).replace('b',regb)\n",
    "        p='^'+p+'$'\n",
    "        m=re.match(p,value)\n",
    "        if m:\n",
    "            if len(set(m.groups()))==len(m.groups()):\n",
    "                return True\n",
    "            else:\n",
    "                return False\n",
    "        else:\n",
    "            return False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# class Solution:\n",
    "#     def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "#         n = len(value)\n",
    "#         if len(pattern) == 0:\n",
    "#             return True\n",
    "#         pn = dict(collections.Counter(pattern))\n",
    "#         if n==0:\n",
    "#             if len(pattern)==1:\n",
    "#                 return True\n",
    "#             else:\n",
    "#                 return False\n",
    "#         for pk, pv in pn.items():\n",
    "#             if pk not in ['a', 'b']:   #出现其它字符\n",
    "#                 return False\n",
    "#             if (pk == 'a' and len(pn)==pn[pk]) or (pk == 'b' and len(pn)==pn[pk]):    #全为a\n",
    "#                 if n%pn[pk] != 0:\n",
    "#                     return False\n",
    "#                 d, judge = n//pn[pk], set()  #用集合来判断value串中是否有第二种存在\n",
    "#                 for i in range(pn[pk]):\n",
    "#                     judge.add(value[i*d:i*d+d])\n",
    "#                     if len(judge)>1:\n",
    "#                         break\n",
    "#                 if len(judge)==1:\n",
    "#                     return True\n",
    "#         if 'a' in pn.keys() and pn['a'] > 0 and 'b' in pn.keys() and pn['b'] > 0:\n",
    "#             for i in range(n//pn['a']+1):\n",
    "#                 if (n-i*pn['a'])%pn['b'] == 0:\n",
    "#                     j = (n-i*pn['a'])//pn['b']\n",
    "#                     cur, judge1, judge2 = 0, set(), set()\n",
    "#                     for ch in pattern:  #分别判断两个集合中是否有第二种字符串存在\n",
    "#                         if ch == 'a':\n",
    "#                             judge1.add(value[cur:cur+i])\n",
    "#                             cur += i\n",
    "#                         else:\n",
    "#                             judge2.add(value[cur:cur+j])\n",
    "#                             cur += j\n",
    "#                         if len(judge1) > 1 and len(judge2) > 1:\n",
    "#                             break\n",
    "#                     if len(judge1) == 1 and len(judge2) == 1:\n",
    "#                         return True\n",
    "#         return False\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        plen, vlen = len(pattern), len(value)\n",
    "        if plen == 0 and vlen == 0:\n",
    "            return True\n",
    "        elif plen == 0 and vlen != 0:\n",
    "            return False\n",
    "        elif plen != 0 and vlen == 0:\n",
    "            if pattern.count('a')==len(pattern) or pattern.count('b')==len(pattern):\n",
    "                return True\n",
    "            else:\n",
    "                return False\n",
    "        else:\n",
    "            ca, cb = pattern.count('a'), pattern.count('b')\n",
    "            #只含有两字符中的一种\n",
    "            if ca==len(pattern) or cb==len(pattern):\n",
    "                if len(value)%len(pattern)==0:\n",
    "                    k = len(value)//len(pattern)   #表示匹配上的长度\n",
    "                    resa, resb = set(), set()\n",
    "                    cur = 0\n",
    "                    for c in pattern:\n",
    "                        if c== 'a':\n",
    "                            resa.add(value[cur:cur+k])\n",
    "                            cur += k\n",
    "                        if c == 'b':\n",
    "                            resb.add(value[cur:cur+k])\n",
    "                            cur += k\n",
    "                    print(resa, resb)\n",
    "                    if len(resa)==1 or len(resb)==1:\n",
    "                        return True\n",
    "                    else:\n",
    "                        return False\n",
    "                else:\n",
    "                    return False\n",
    "            #某个字符只有一个，将多的字符匹配\"\"，该字符匹配value\n",
    "            elif ca==1 or cb==1:\n",
    "                return True\n",
    "            elif ca>1 and cb>1:\n",
    "                ka = len(value)//ca   #表示匹配上a的长度\n",
    "                for i in range(1, ka+1):    #遍历a所有可能取到的长度\n",
    "                    if (len(value)-i*ca)%cb == 0:\n",
    "                        kb = (len(value)-i*ca)//cb  #剩余的部分匹配b的长度\n",
    "                        resa, resb = set(), set()\n",
    "                        cur = 0\n",
    "                        for c in pattern:\n",
    "                            if c == 'a':\n",
    "                                print(i, value[cur:cur+i])\n",
    "                                resa.add(value[cur:cur+i])\n",
    "                                cur += i\n",
    "                            elif c == 'b':\n",
    "                                resb.add(value[cur:cur+kb])\n",
    "                                cur += kb\n",
    "                        print(resa, resb)\n",
    "                        if len(resa)==1 and len(resb)==1 and resa != resb:\n",
    "                            return True\n",
    "                return False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        # 边界情况处理\n",
    "        if not pattern: return not value\n",
    "        if len(pattern) == 1: return True\n",
    "\n",
    "        # 构造正则表达式：重点是正则表达式的“后向引用”\n",
    "        rega, regb = ('\\\\1', '\\\\2') if pattern[0] == 'a' else ('\\\\2', '\\\\1')\n",
    "        p = pattern.replace('a', '(\\\\w*)', 1).replace('b', '(\\\\w*)', 1).replace('a', rega).replace('b', regb)\n",
    "        p = '^' + p + '$'\n",
    "        m = re.match(p, value)\n",
    "        if m:          \n",
    "            # 匹配到 && (模式长度为1 || 模式长度为2 && 两个模式不相同)\n",
    "            if len(set(m.groups()))==len(m.groups()):\n",
    "                return True\n",
    "            else:\n",
    "                return False\n",
    "        else:\n",
    "            return False\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        cnta, cntb, n = 0, 0, len(value)         # 计算a和b的个数，n为value长度\n",
    "        for ch in pattern:\n",
    "            if ch == 'a': cnta += 1\n",
    "            else: cntb += 1\n",
    "        \n",
    "        if n == 0:                               # 判断各种边界情况，pattern或者value为空\n",
    "            return cnta * cntb == 0\n",
    "        else:\n",
    "            if cnta == 0 and cntb == 0:\n",
    "                return False\n",
    "            elif cnta == 0 or cntb == 0:         # 判断pattern全是a或者全是b的情况\n",
    "                if cnta == 0:\n",
    "                    cnta, cntb = cntb, cnta      # 如果cnta为0，两者调换一下\n",
    "                if n % cnta != 0:                # 不能整除的情况\n",
    "                    return False\n",
    "                d, judge = n//cnta, set()        # 用集合来判断是否有第二种字符串出现\n",
    "                for i in range(cnta):\n",
    "                    judge.add(value[i*d:i*d+d])\n",
    "                    if len(judge) > 1: break\n",
    "                return len(judge) == 1           # 如果自始至终只有一种字符串，那么就是True\n",
    "\n",
    "        for i in range(0, n//cnta+1):            # 一般情况\n",
    "            if (n-i*cnta) % cntb == 0:           # 只判断能整除的情况\n",
    "                j = (n-i*cnta)//cntb\n",
    "                cur, judge1, judge2 = 0, set(), set()\n",
    "                for ch in pattern:               # 分别判断两个集合是否有第二种字符串出现\n",
    "                    if ch == 'a':\n",
    "                        judge1.add(value[cur:cur + i])\n",
    "                        cur += i\n",
    "                    else:\n",
    "                        judge2.add(value[cur:cur + j])\n",
    "                        cur += j\n",
    "                    if len(judge1) > 1 and len(judge2) > 1:\n",
    "                        break\n",
    "                if len(judge1) == 1 and len(judge2) == 1 and judge1!=judge2:\n",
    "                    return True                   # 如果两个集合都只有一种字符串，那么就是True\n",
    "        return False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        if not pattern:return not value\n",
    "        if len(pattern)==1:return True\n",
    "        a,b = ('\\\\1','\\\\2') if pattern[0]=='a' else ('\\\\2','\\\\1')\n",
    "        p = pattern.replace('a','(\\\\w*)',1).replace('b','(\\\\w*)',1).replace('a',a).replace('b',b)\n",
    "        res = re.match('^'+p+'$',value)\n",
    "        return bool(res and (len(res.groups())==1 or res.groups()[0]!=res.groups()[1]))\n",
    "\n",
    "\n",
    "        # n = len(value)\n",
    "        # ma,mb = pattern.count('a'),pattern.count('b')\n",
    "        # if n==0:\n",
    "        #     if ma*mb==0:return True\n",
    "        #     else:return False\n",
    "        # if ma==1 or mb==1:return True\n",
    "        # if ma==0 and mb==0:return False\n",
    "        # if ma<mb:\n",
    "        #     pattern = pattern.replace('a','c').replace('b','a').replace('c','b')\n",
    "        #     ma,mb = mb,ma\n",
    "        # for x in range(n//ma+1):\n",
    "        #     dicts = {}\n",
    "        #     if mb!=0:\n",
    "        #         y = (n-ma*x)/mb\n",
    "        #         if y!=int(y):continue\n",
    "        #         else:y=int(y)\n",
    "        #     sta = 0\n",
    "        #     for i in range(ma+mb):\n",
    "        #         if pattern[i]=='a':\n",
    "        #             dicts[pattern[i]] = value[sta:sta+x]\n",
    "        #             sta += x\n",
    "        #         else:\n",
    "        #             dicts[pattern[i]] = value[sta:sta+y]\n",
    "        #             sta+=y\n",
    "        #         if mb==0 or len(dicts)==2:break\n",
    "        #     if mb!=0 and dicts['a']==dicts['b']:continue\n",
    "        #     acc = ''\n",
    "        #     for c in pattern:\n",
    "        #         acc+=dicts[c]\n",
    "        #     if acc==value:\n",
    "        #         return True\n",
    "        # return False\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        # 按pattern分配a、b长度：先求数量，再搜索不定方程整数解\n",
    "        np = len(pattern)\n",
    "        lv = len(value)\n",
    "        if lv == 0 and np == 1:\n",
    "            return True\n",
    "        na = 0\n",
    "        nb = 0\n",
    "        la_lbs = []  # a、b可能长度对\n",
    "        for x in pattern:\n",
    "            if x == \"a\":\n",
    "                na += 1\n",
    "            else:\n",
    "                nb += 1\n",
    "        if na == 0:\n",
    "            if lv % nb == 0:\n",
    "                la_lbs.append([0, lv // nb])\n",
    "        else:\n",
    "            for la in range(lv // na + 1):\n",
    "                if nb == 0:\n",
    "                    if lv == la * na:  # 没有b且a长度满足要求\n",
    "                        la_lbs.append([la, 0])\n",
    "                elif (lv - la * na) % nb == 0:\n",
    "                    la_lbs.append([la, (lv - la * na) // nb])\n",
    "        if len(la_lbs) == 0:  # pattern长度无法匹配\n",
    "            return False\n",
    "\n",
    "        #  对每个可能的长度对，找到a、b对应位置的字符串，遍历并匹配 \n",
    "        for la_lb in la_lbs:\n",
    "            start_idx = 0  # 当前匹配子串索引\n",
    "            a, b = \"\", \"\"\n",
    "            la, lb = la_lb[0], la_lb[1]\n",
    "            flag = False\n",
    "            for x in pattern:\n",
    "                if x == \"a\":\n",
    "                    cur_a = value[start_idx:start_idx+la]\n",
    "                    start_idx = start_idx + la\n",
    "                    # print(cur_a)\n",
    "                    # print(a)\n",
    "                    if not a:\n",
    "                       a = cur_a # 第一个a匹配的子串\n",
    "                       flag = True\n",
    "                    elif cur_a != a:  # 不同的a对应不同子串，匹配失败\n",
    "                        flag = False\n",
    "                        break\n",
    "                    else:\n",
    "                        flag = True\n",
    "                elif x == \"b\":\n",
    "                    cur_b = value[start_idx:start_idx+lb]\n",
    "                    start_idx = start_idx + lb\n",
    "                    if not b:\n",
    "                        b = cur_b # 第一个a匹配的子串\n",
    "                        flag = True\n",
    "                    elif cur_b != b:  # 不同的a对应不同子串，匹配失败\n",
    "                        flag = False\n",
    "                        break\n",
    "                    else:\n",
    "                        flag = True\n",
    "            if flag and a != b:  # 如果完全匹配且ab不同则返回True\n",
    "                return True\n",
    "        return False  # 全部长度均失败\n",
    "\n",
    "            \n",
    "\n",
    "\n",
    "\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        def check(la: int, lb: int) -> bool:\n",
    "            i = 0\n",
    "            a, b = '', ''\n",
    "            for c in pattern:\n",
    "                if c == 'a':\n",
    "                    if a and value[i: i + la] != a:\n",
    "                        return False\n",
    "                    a = value[i: i + la]\n",
    "                    i += la\n",
    "                else:\n",
    "                    if b and value[i: i + lb] != b:\n",
    "                        return False\n",
    "                    b = value[i: i + lb]\n",
    "                    i += lb\n",
    "            return a != b\n",
    "\n",
    "        n = len(value)\n",
    "        cnt = Counter(pattern)\n",
    "        # if cnt['a'] == 0:\n",
    "        #     return n % cnt['b'] == 0 and value[: n // cnt['b']] * cnt['b'] == value\n",
    "        if cnt['b'] == 0:\n",
    "            return n % cnt['a'] == 0 and value[: n // cnt['a']] * cnt['a'] == value\n",
    "        \n",
    "        for la in range(n + 1):\n",
    "            if la * cnt['a'] > n:\n",
    "                break\n",
    "            lb, mod = divmod(n - la * cnt['a'], cnt['b'])\n",
    "            if mod == 0 and check(la, lb):\n",
    "                return True\n",
    "        return False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        n = len(value)\n",
    "        ma,mb = pattern.count('a'),pattern.count('b')\n",
    "        if n==0:\n",
    "            if ma*mb==0:return True\n",
    "            else:return False\n",
    "        if ma==1 or mb==1:return True\n",
    "        if ma==0 and mb==0:return False\n",
    "        if ma<mb:\n",
    "            pattern = pattern.replace('a','c').replace('b','a').replace('c','b')\n",
    "            ma,mb = mb,ma\n",
    "        # print(pattern,ma,mb)\n",
    "        for x in range(n//ma+1):\n",
    "            dicts = {}\n",
    "            if mb!=0:\n",
    "                y = (n-ma*x)/mb\n",
    "                if y!=int(y):continue\n",
    "                else:y=int(y)\n",
    "            sta = 0\n",
    "            for i in range(ma+mb):\n",
    "                if pattern[i]=='a':\n",
    "                    dicts[pattern[i]] = value[sta:sta+x]\n",
    "                    sta += x\n",
    "                else:\n",
    "                    dicts[pattern[i]] = value[sta:sta+y]\n",
    "                    sta+=y\n",
    "                if mb==0 or len(dicts)==2:break\n",
    "            if mb!=0 and dicts['a']==dicts['b']:continue\n",
    "            # print(dicts)\n",
    "            acc = ''\n",
    "            for c in pattern:\n",
    "                acc+=dicts[c]\n",
    "            # print(acc)\n",
    "            if acc==value:\n",
    "                return True\n",
    "        return False\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        np, nv, na, fep = len(pattern), len(value), pattern.count('a'), list()\n",
    "        if np == na:\n",
    "            if nv % np == 0:\n",
    "                fep.append([nv//np, 0])\n",
    "        elif na == 0:\n",
    "            if nv % np == 0:\n",
    "                fep.append([0, nv//np])\n",
    "        else:\n",
    "            for i in range(0, int(nv//na) + 1):\n",
    "                if (nv - i*na) % (np - na) == 0:\n",
    "                    fep.append([i, (nv - i*na) // (np - na)])\n",
    "\n",
    "        if not fep:\n",
    "            return False\n",
    "        print(len(fep))\n",
    "        for i, k in fep:\n",
    "            fa, fb, index = False, False, 0\n",
    "            ta, tb = value, value\n",
    "            for p in pattern:\n",
    "                if p == \"a\":\n",
    "                    if not fa:\n",
    "                        ta = value[index: index + i]\n",
    "                        fa = True\n",
    "                    else:\n",
    "                        if value[index: index + i] != ta:\n",
    "                            break\n",
    "                    index += i\n",
    "                else:\n",
    "                    if not fb:\n",
    "                        tb = value[index: index + k]\n",
    "                        fb = True\n",
    "                    else:\n",
    "                        if value[index: index + k] != tb:\n",
    "                            break\n",
    "                    index += k\n",
    "            if fa and fb:\n",
    "                if ta == tb:\n",
    "                    break\n",
    "            if index == nv:\n",
    "                return True\n",
    "\n",
    "        return False\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        a_count = pattern.count(\"a\") if \"a\" in pattern else 0\n",
    "        b_count = pattern.count(\"b\") if \"b\" in pattern else 0\n",
    "        n = len(value)\n",
    "\n",
    "        if a_count == 0 or b_count == 0:\n",
    "            x_count = a_count + b_count\n",
    "            x_len = n//x_count\n",
    "            x = value[:x_len]\n",
    "            return x_count * x == value\n",
    "\n",
    "        for a_len in range(0, n//a_count+1):\n",
    "            b_len = (n - a_len*a_count) // b_count\n",
    "            if (a_len * a_count + b_len * b_count) == n:\n",
    "                p2str = {}\n",
    "                x, x_len, y, y_len = ('a', a_len, 'b', b_len) if pattern.startswith('a') else ('b', b_len, 'a', a_len)\n",
    "                p2str[x] = value[:x_len]\n",
    "                ind = pattern.find(y)\n",
    "                p2str[y] = value[ind*x_len:(ind*x_len+y_len)]\n",
    "\n",
    "                value_pattern = \"\".join([p2str[p] for p in pattern])\n",
    "                if value_pattern == value and  p2str[x] !=  p2str[y]:\n",
    "                    return True\n",
    "\n",
    "        return False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        if pattern[0]=='b':\n",
    "            pattern = pattern.replace('a', 'c').replace('b', 'a').replace('c', 'b')\n",
    "        xa, xb = pattern.count('a'), pattern.count('b')\n",
    "        if xb == 0:\n",
    "            a = value[:len(value)//xa]\n",
    "            return a*xa == value\n",
    "        print(pattern)\n",
    "        for i in range(len(value)+1):\n",
    "            if (len(value)-xa*i)%xb==0:\n",
    "                a, b, s = value[:i], None, ''\n",
    "                for alpha in pattern:\n",
    "                    if alpha == 'a': s += a\n",
    "                    else:\n",
    "                        if b == None: b = value[len(s):len(s)+(len(value)-xa*i)//xb]\n",
    "                        s += b\n",
    "                s = ''.join((a, b)[alpha=='b'] for alpha in pattern)\n",
    "                if s == value and a!=b: return True\n",
    "        return False\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        if pattern == \"\":\n",
    "            return value == \"\"\n",
    "        \n",
    "        if value == \"\":\n",
    "            return len(set(pattern)) == 1\n",
    "        \n",
    "        n = len(pattern)\n",
    "        m = len(value)\n",
    "        print(n, m)\n",
    "        cnt1 = cnt2 = 0\n",
    "        for char in pattern:\n",
    "            if char == \"a\":\n",
    "                cnt1 += 1\n",
    "            else:\n",
    "                cnt2 += 1\n",
    "        \n",
    "        def fun1(cnt, value):\n",
    "            if len(value) % cnt != 0:\n",
    "                return False\n",
    "            num = len(value) // cnt\n",
    "            return all(value[:num] == value[i*num:(i+1)*num] for i in range(1, cnt))\n",
    "\n",
    "        if cnt1 == 0:\n",
    "            return fun1(cnt2, value)\n",
    "        if cnt2 == 0:\n",
    "            return fun1(cnt1, value)\n",
    "        if cnt1 == 1 or cnt2 == 1:\n",
    "            return True\n",
    "\n",
    "        def camDo(lena, lenb, value):\n",
    "            a = \"A\"\n",
    "            b = \"A\"\n",
    "            index = 0\n",
    "            for char in pattern:\n",
    "                if char == \"a\":\n",
    "                    if a == \"A\":\n",
    "                        a = value[index:index + lena]\n",
    "                    else:\n",
    "                        if value[index:index + lena] != a:\n",
    "                            print(lena, lenb)\n",
    "                            return False\n",
    "                    index += lena\n",
    "                if char == \"b\":\n",
    "                    if b == \"A\":\n",
    "                        b = value[index: index + lenb]\n",
    "                    else:\n",
    "                        if value[index: index + lenb] != b:\n",
    "                            print(lena, lenb)\n",
    "                            return False\n",
    "                    index += lenb\n",
    "            return True if a != b else False\n",
    "        \n",
    "        for lena in range(m // cnt1):\n",
    "            lenb = (m - cnt1 * lena) / cnt2\n",
    "            if lenb % 1 == 0 and camDo(lena, int(lenb), value):\n",
    "                return True\n",
    "        return False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        \n",
    "    \n",
    "        import re\n",
    "\n",
    "        # a为\\1 b为\\2\n",
    "        rega, regb = ('\\\\1', '\\\\2') if pattern[0] == 'a' else ('\\\\2', '\\\\1')\n",
    "\n",
    "        p = pattern.replace('a', '(\\\\w*)', 1).replace('b', '(\\\\w*)', 1).replace('a', rega).replace('b', regb)\n",
    "\n",
    "        p = '^' + p + '$'\n",
    "        m = re.match(p, value)\n",
    "        \n",
    "        if not m:\n",
    "            return False\n",
    "        if len(m.groups()) == 1:\n",
    "            return True\n",
    "        if not m.groups() or m.groups()[0]==m.groups()[1]:\n",
    "            return False\n",
    "        return True\n",
    "\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        n = len(value)\n",
    "        ma,mb = pattern.count('a'),pattern.count('b')\n",
    "        if n==0:\n",
    "            if ma*mb==0:return True\n",
    "            else:return False\n",
    "        if ma==1 or mb==1:return True\n",
    "        if ma==0 and mb==0:return False\n",
    "        if ma<mb:\n",
    "            pattern = pattern.replace('a','c').replace('b','a').replace('c','b')\n",
    "            ma,mb = mb,ma\n",
    "        for x in range(n//ma+1):\n",
    "            dicts = {}\n",
    "            if mb!=0:\n",
    "                y = (n-ma*x)/mb\n",
    "                if y!=int(y):continue\n",
    "                else:y=int(y)\n",
    "            sta = 0\n",
    "            for i in range(ma+mb):\n",
    "                if pattern[i]=='a':\n",
    "                    dicts[pattern[i]] = value[sta:sta+x]\n",
    "                    sta += x\n",
    "                else:\n",
    "                    dicts[pattern[i]] = value[sta:sta+y]\n",
    "                    sta+=y\n",
    "                if mb==0 or len(dicts)==2:break\n",
    "            if mb!=0 and dicts['a']==dicts['b']:continue\n",
    "            acc = ''\n",
    "            for c in pattern:\n",
    "                acc+=dicts[c]\n",
    "            if acc==value:\n",
    "                return True\n",
    "        return False\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        count_a = pattern.count('a')\n",
    "        count_b = len(pattern) - count_a\n",
    "        if count_a < count_b:\n",
    "            count_a, count_b = count_b, count_a\n",
    "            pattern = ''.join('a' if ch == 'b' else 'b' for ch in pattern)\n",
    "        \n",
    "        if not value:\n",
    "            return count_b == 0\n",
    "        \n",
    "        if not pattern:\n",
    "            return False\n",
    "        \n",
    "        for len_a in range(len(value) // count_a + 1):\n",
    "            rest = len(value) - count_a * len_a\n",
    "            if (count_b == 0 and rest == 0) or (count_b != 0 and rest % count_b == 0):\n",
    "                len_b = 0 if count_b == 0 else rest // count_b\n",
    "                pos = 0\n",
    "                valid = True\n",
    "                a, b = None, None\n",
    "                for ch in pattern:\n",
    "                    if ch == 'a':\n",
    "                        sub = value[pos:pos + len_a]\n",
    "                        if a is None:\n",
    "                            a = sub\n",
    "                        elif a != sub:\n",
    "                            valid = False\n",
    "                            break\n",
    "                        pos += len_a\n",
    "                    else:\n",
    "                        sub = value[pos:pos + len_b]\n",
    "                        if b is None:\n",
    "                            b = sub\n",
    "                        elif b != sub:\n",
    "                            valid = False\n",
    "                            break\n",
    "                        pos += len_b\n",
    "                if valid and a != b:\n",
    "                    return True\n",
    "        return False\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        p_counter = Counter(pattern)\n",
    "        str_len = len(value)\n",
    "\n",
    "        if not value:\n",
    "            return (p_counter['a'] == 0 or p_counter['b'] == 0) and not (p_counter['a'] > 0 and p_counter['b'] > 0)\n",
    "\n",
    "        a_max_len = str_len // p_counter['a'] if p_counter['a'] != 0 else 0\n",
    "        b_max_len = str_len // p_counter['b'] if p_counter['b'] != 0 else 0\n",
    "\n",
    "        def do_check(a, b, a_count, b_count):\n",
    "            if a == b:\n",
    "                return False\n",
    "\n",
    "            if len(a) * a_count + len(b) * b_count != str_len:\n",
    "                return False\n",
    "\n",
    "            target = []\n",
    "\n",
    "            for char in pattern:\n",
    "                if char == 'a':\n",
    "                    target.append(a)\n",
    "                else:\n",
    "                    target.append(b)\n",
    "\n",
    "            return ''.join(target) == value\n",
    "\n",
    "        if a_max_len == 0:\n",
    "            b_len = str_len // p_counter['b']\n",
    "            b = value[:b_len]\n",
    "            if do_check('', b, 0, p_counter['b']):\n",
    "                return True\n",
    "\n",
    "        elif b_max_len == 0:\n",
    "            a_len = str_len // p_counter['a']\n",
    "            a = value[:a_len]\n",
    "            if do_check(a, '', p_counter['a'], p_counter['b']):\n",
    "                return True\n",
    "\n",
    "        else:\n",
    "            for a_len in range(a_max_len + 1):\n",
    "                b_len = (str_len - a_len * p_counter['a']) // p_counter['b']\n",
    "                a_index = pattern.index('a')\n",
    "                b_index = pattern.index('b')\n",
    "                if a_index == 0:\n",
    "                    a = value[:a_len]\n",
    "                    b = value[b_index * a_len: b_index * a_len + b_len]\n",
    "                else:\n",
    "                    b = value[:b_len]\n",
    "                    a = value[a_index * b_len: a_index * b_len + a_len]\n",
    "                if do_check(a, b, p_counter['a'], p_counter['b']):\n",
    "                    return True\n",
    "\n",
    "        return False\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        if not value  and not pattern:return True\n",
    "        if not pattern: return False\n",
    "        if not value:return len(pattern)==1\n",
    "\n",
    "        count_a ,count_b=0,0\n",
    "        for i in pattern:\n",
    "            if i == 'a':\n",
    "                count_a +=1\n",
    "            else:\n",
    "                count_b +=1\n",
    "        if count_a * count_b ==0:\n",
    "            length = len(value)//(count_a+count_b)\n",
    "            return value[:length]*(count_a+count_b)==value\n",
    "\n",
    "        if count_a ==1 or count_b == 1:return True\n",
    "\n",
    "        for i in range(len(value)):\n",
    "            remain = len(value)- count_a *i\n",
    "            if remain %count_b != 0:continue\n",
    "            if remain <0: break\n",
    "            j = remain //count_b\n",
    "            set_A=set()\n",
    "            setB=set()\n",
    "            p=0\n",
    "            for s in pattern:\n",
    "                if s =='a':\n",
    "                    set_A.add(value[p:p+i])\n",
    "                    p+= i\n",
    "                else:\n",
    "                    setB.add(value[p:p+j])\n",
    "                    p+= j\n",
    "            if len(set_A) == len(setB) == 1 and set_A !=setB:\n",
    "                return True\n",
    "        return False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        # 边界情况处理\n",
    "        if not pattern: return not value\n",
    "        if len(pattern) == 1: return True\n",
    "\n",
    "        # 构造正则表达式：重点是正则表达式的“后向引用”\n",
    "        rega, regb = ('\\\\1', '\\\\2') if pattern[0] == 'a' else ('\\\\2', '\\\\1')\n",
    "        p = pattern.replace('a', '(\\\\w*)', 1).replace('b', '(\\\\w*)', 1).replace('a', rega).replace('b', regb)\n",
    "        p = '^' + p + '$'\n",
    "        m = re.match(p, value)\n",
    "        if m:          \n",
    "            # 匹配到 && (模式长度为1 || 模式长度为2 && 两个模式不相同)\n",
    "            if len(set(m.groups()))==len(m.groups()):\n",
    "                return True\n",
    "            else:\n",
    "                return False\n",
    "        else:\n",
    "            return False\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        a_count = pattern.count(\"a\") if \"a\" in pattern else 0\n",
    "        b_count = pattern.count(\"b\") if \"b\" in pattern else 0\n",
    "        n = len(value)\n",
    "\n",
    "        if a_count == 0 or b_count == 0:\n",
    "            x_count = a_count + b_count\n",
    "            x_len = n//x_count\n",
    "            x = value[:x_len]\n",
    "            return x_count * x == value\n",
    "\n",
    "        x, x_count, y, y_count = ('a', a_count, 'b', b_count) if pattern.startswith('a') else ('b', b_count, 'a', a_count)\n",
    "        y_begin_ind = pattern.find(y)\n",
    "        p2str = {}\n",
    "        for x_len in range(0, n//x_count+1):\n",
    "            y_len = (n - x_len*x_count) // y_count\n",
    "            if (x_len * x_count + y_len * y_count) == n:\n",
    "                p2str[x] = value[:x_len]\n",
    "                p2str[y] = value[y_begin_ind*x_len:(y_begin_ind*x_len+y_len)]\n",
    "                value_pattern = \"\".join([p2str[p] for p in pattern])\n",
    "                if p2str[x] != p2str[y] and value_pattern == value:\n",
    "                    return True\n",
    "\n",
    "        return False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        a_count = pattern.count(\"a\") if \"a\" in pattern else 0\n",
    "        b_count = pattern.count(\"b\") if \"b\" in pattern else 0\n",
    "        n = len(value)\n",
    "\n",
    "        \n",
    "        if a_count == 0:\n",
    "            b_len = n//b_count\n",
    "            b = value[:b_len]\n",
    "            return b_count * b == value\n",
    "        elif b_count == 0:\n",
    "            a_len = n//a_count\n",
    "            a = value[:a_len]\n",
    "            return a_count * a == value\n",
    "\n",
    "        for a_len in range(0, n//a_count+1):\n",
    "            b_len = (n - a_len*a_count) // b_count\n",
    "            if (a_len * a_count + b_len * b_count) == n:\n",
    "                p2str = {}\n",
    "                if pattern.startswith('a'):\n",
    "                    p2str[\"a\"] = value[:a_len]\n",
    "                    ind = pattern.find('b')\n",
    "                    p2str[\"b\"] = value[ind*a_len:(ind*a_len+b_len)]\n",
    "                else:\n",
    "                    p2str[\"b\"] = value[:b_len]\n",
    "                    ind = pattern.find('a')\n",
    "                    p2str[\"a\"] = value[ind*b_len:(ind*b_len+a_len)]\n",
    "                value_pattern = \"\".join([p2str[p] for p in pattern])\n",
    "                if value_pattern == value and  p2str[\"a\"] !=  p2str[\"b\"]:\n",
    "                    return True\n",
    "        return False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        # def match(pattern: str, value: str):\n",
    "        #     m, n = len(pattern), len(value)\n",
    "        #     if m == 0:\n",
    "        #         return False\n",
    "        #     if n % m:\n",
    "        #         return False\n",
    "        #     k = n // m\n",
    "        #     count = Counter()\n",
    "        #     for i, p in enumerate(pattern):\n",
    "        #         v = value[i * k: (i + 1) * k]\n",
    "        #         if p not in count:\n",
    "        #             count[p] = v \n",
    "        #         else:\n",
    "        #             if count[p] != v:\n",
    "        #                 return False\n",
    "        #     if count[\"a\"] == count[\"b\"]:\n",
    "        #         return False\n",
    "        #     return True\n",
    "        # if not value and len(set(pattern)) != 1:\n",
    "        #     return False\n",
    "        # if match(pattern, value) or \\\n",
    "        #    match(pattern.replace(\"a\", \"\"), value) or \\\n",
    "        #    match(pattern.replace(\"b\", \"\"), value):\n",
    "        #     return True\n",
    "        # return False\n",
    "        count_a = sum(1 for ch in pattern if ch == 'a')\n",
    "        count_b = len(pattern) - count_a\n",
    "        if count_a < count_b:\n",
    "            count_a, count_b = count_b, count_a\n",
    "            pattern = ''.join('a' if ch == 'b' else 'b' for ch in pattern)\n",
    "        \n",
    "        if not value:\n",
    "            return count_b == 0\n",
    "        if not pattern:\n",
    "            return False\n",
    "        \n",
    "        for len_a in range(len(value) // count_a + 1):\n",
    "            rest = len(value) - count_a * len_a\n",
    "            if (count_b == 0 and rest == 0) or (count_b != 0 and rest % count_b == 0):\n",
    "                len_b = 0 if count_b == 0 else rest // count_b\n",
    "                pos, correct = 0, True\n",
    "                value_a, value_b = None, None\n",
    "                for ch in pattern:\n",
    "                    if ch == 'a':\n",
    "                        sub = value[pos:pos+len_a]\n",
    "                        if not value_a:\n",
    "                            value_a = sub\n",
    "                        elif value_a != sub:\n",
    "                            correct = False\n",
    "                            break\n",
    "                        pos += len_a\n",
    "                    else:\n",
    "                        sub = value[pos:pos+len_b]\n",
    "                        if not value_b:\n",
    "                            value_b = sub\n",
    "                        elif value_b != sub:\n",
    "                            correct = False\n",
    "                            break\n",
    "                        pos += len_b\n",
    "                if correct and value_a != value_b:\n",
    "                    return True\n",
    "        \n",
    "        return False\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        # 边界情况处理\n",
    "        if not pattern: return not value\n",
    "        if len(pattern) == 1: return True\n",
    "\n",
    "        # 构造正则表达式：重点是正则表达式的“后向引用”\n",
    "        rega, regb = ('\\\\1', '\\\\2') if pattern[0] == 'a' else ('\\\\2', '\\\\1')\n",
    "        p = pattern.replace('a', '(\\\\w*)', 1).replace('b', '(\\\\w*)', 1).replace('a', rega).replace('b', regb)\n",
    "        p = '^' + p + '$'\n",
    "        m = re.match(p, value)\n",
    "\n",
    "        # 匹配到 && (模式长度为1 || 模式长度为2 && 两个模式不相同)\n",
    "        return bool(m and (len(m.groups()) == 1 or m.groups()[0] != m.groups()[1]))\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        \n",
    "        if pattern[0]==\"b\":\n",
    "            pattern = list(pattern)\n",
    "            for i in range(len(pattern)):\n",
    "                if pattern[i]==\"a\":\n",
    "                    pattern[i] = \"b\"\n",
    "                else:\n",
    "                    pattern[i] = \"a\"\n",
    "        pattern = \"\".join(pattern)\n",
    "        nums_a = 0\n",
    "        nums_b = 0\n",
    "        for i in range(len(pattern)):\n",
    "            if pattern[i] == \"a\":\n",
    "                nums_a += 1\n",
    "            if pattern[i] == \"b\":\n",
    "                nums_b += 1\n",
    "        if len(value)==0:\n",
    "            if nums_a*nums_b==0:\n",
    "                return True\n",
    "            else:\n",
    "                return False\n",
    "        len_value = len(value)\n",
    "        a_maxlen = len_value//nums_a\n",
    "        # 保证pattern的首字母为a, 其实没必要，因为这题的abba等价于baab\n",
    "        a_dict = {}\n",
    "        print(pattern)\n",
    "        print(a_maxlen)\n",
    "        first_b_index = 0  # 记录b第一次出现的位置\n",
    "        for i in range(len(pattern)):\n",
    "            if pattern[i]==\"b\":\n",
    "                first_b_index = i\n",
    "                break\n",
    "        for i in range(a_maxlen+1):\n",
    "            a_dict[\"a\"] = value[0:i]\n",
    "            if nums_b != 0:\n",
    "                b_len = (len_value-nums_a*i)//nums_b\n",
    "                a_dict[\"b\"] = value[i*first_b_index:i*first_b_index+b_len]\n",
    "            else:\n",
    "                a_dict[\"b\"] = \"\"\n",
    "            temp = \"\"\n",
    "            print(a_dict[\"a\"])\n",
    "            print(a_dict[\"b\"])\n",
    "            for j in pattern:\n",
    "                temp += a_dict[j]\n",
    "            if temp == value and a_dict[\"a\"]!=a_dict[\"b\"]:\n",
    "                return True\n",
    "        return False\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        used = set()\n",
    "        data = {}\n",
    "\n",
    "        def dfs(pattern, value, data, used):\n",
    "            if len(pattern) == 0:\n",
    "                return len(value) == 0\n",
    "\n",
    "            p = pattern[0]\n",
    "            if p in data:\n",
    "                word = data[p]\n",
    "                if word != value[:len(word)]: return False\n",
    "                return dfs(pattern[1:], value[len(word):], data, used)\n",
    "\n",
    "            for i in range(len(value)+1):\n",
    "                word = value[:i]\n",
    "                if word in used: continue\n",
    "                used.add(word)\n",
    "                data[p] = word\n",
    "                if dfs(pattern[1:], value[len(word):], data, used): return True\n",
    "\n",
    "                used.remove(word)\n",
    "                del data[p]\n",
    "\n",
    "            return False\n",
    "\n",
    "        return dfs(pattern, value, data, used)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        if pattern[0] == 'a':\n",
    "            rega = '\\\\1'\n",
    "            regb = '\\\\2'\n",
    "        else:\n",
    "            rega = '\\\\2'\n",
    "            regb = '\\\\1'\n",
    "        \n",
    "        p = pattern.replace('a', '(\\\\w*)', 1).replace('b', '(\\\\w*)', 1)\n",
    "        p = p.replace('a', rega).replace('b', regb)\n",
    "        p = '^'+p+'$'\n",
    "        res = re.match(p, value)\n",
    "        if res:\n",
    "            if len(res.groups()) == 1:\n",
    "                return True \n",
    "            if res.groups()[0] != res.groups()[1]:\n",
    "                return True \n",
    "        return False \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# class Solution:\n",
    "#     def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "#         if not len(pattern) and not len(value): return True\n",
    "#         if not len(value): return False\n",
    "#         if pattern == 'ab': return True\n",
    "#         res = False\n",
    "#         def handle(pattern, s, a, b):\n",
    "#             nonlocal res\n",
    "#             if res: return\n",
    "#             if not len(pattern) and not len(s):\n",
    "#                 res = True\n",
    "#                 return\n",
    "#             if not len(pattern) or not len(s): return\n",
    "#             if pattern[0] == 'a':\n",
    "#                 if a is not None:\n",
    "#                     if s[:len(a)] == a:\n",
    "#                         handle(pattern[1:], s[len(a):], a, b)\n",
    "#                 else:\n",
    "#                     for i in range(len(s)+1):\n",
    "#                         if s[:i] == b: continue\n",
    "#                         handle(pattern[1:], s[i:], s[:i], b)\n",
    "#             elif pattern[0] == 'b':\n",
    "#                 if b is not None:\n",
    "#                     if s[:len(b)] == b:\n",
    "#                         handle(pattern[1:], s[len(b):], a, b)\n",
    "#                 else:\n",
    "#                     for i in range(len(s)+1):\n",
    "#                         if s[:i] == a: continue\n",
    "#                         handle(pattern[1:], s[i:], a, s[:i])\n",
    "        \n",
    "#         handle(pattern, value, None, None)\n",
    "#         return res\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        count_a = sum(1 for ch in pattern if ch == 'a')\n",
    "        count_b = len(pattern) - count_a\n",
    "        if count_a < count_b:\n",
    "            count_a, count_b = count_b, count_a\n",
    "            pattern = ''.join('a' if ch == 'b' else 'b' for ch in pattern)\n",
    "        \n",
    "        if not value:\n",
    "            return count_b == 0\n",
    "        if not pattern:\n",
    "            return False\n",
    "        \n",
    "        for len_a in range(len(value) // count_a + 1):\n",
    "            rest = len(value) - count_a * len_a\n",
    "            if (count_b == 0 and rest == 0) or (count_b != 0 and rest % count_b == 0):\n",
    "                len_b = 0 if count_b == 0 else rest // count_b\n",
    "                pos, correct = 0, True\n",
    "                value_a, value_b = None, None\n",
    "                for ch in pattern:\n",
    "                    if ch == 'a':\n",
    "                        sub = value[pos:pos+len_a]\n",
    "                        if not value_a:\n",
    "                            value_a = sub\n",
    "                        elif value_a != sub:\n",
    "                            correct = False\n",
    "                            break\n",
    "                        pos += len_a\n",
    "                    else:\n",
    "                        sub = value[pos:pos+len_b]\n",
    "                        if not value_b:\n",
    "                            value_b = sub\n",
    "                        elif value_b != sub:\n",
    "                            correct = False\n",
    "                            break\n",
    "                        pos += len_b\n",
    "                if correct and value_a != value_b:\n",
    "                    return True\n",
    "        \n",
    "        return False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        \n",
    "        if pattern[0]==\"b\":\n",
    "            pattern = list(pattern)\n",
    "            for i in range(len(pattern)):\n",
    "                if pattern[i]==\"a\":\n",
    "                    pattern[i] = \"b\"\n",
    "                else:\n",
    "                    pattern[i] = \"a\"\n",
    "        pattern = \"\".join(pattern)\n",
    "        nums_a = 0\n",
    "        nums_b = 0\n",
    "        for i in range(len(pattern)):\n",
    "            if pattern[i] == \"a\":\n",
    "                nums_a += 1\n",
    "            if pattern[i] == \"b\":\n",
    "                nums_b += 1\n",
    "        if len(value)==0:\n",
    "            if nums_a*nums_b==0:\n",
    "                return True\n",
    "            else:\n",
    "                return False\n",
    "        len_value = len(value)\n",
    "        a_maxlen = len_value//nums_a\n",
    "        # 保证pattern的首字母为a, 其实没必要，因为这题的abba等价于baab\n",
    "        a_dict = {}\n",
    "        print(pattern)\n",
    "        print(a_maxlen)\n",
    "        first_b_index = 0\n",
    "        for i in range(len(pattern)):\n",
    "            if pattern[i]==\"b\":\n",
    "                first_b_index = i\n",
    "                break\n",
    "        for i in range(a_maxlen+1):\n",
    "\n",
    "            a_dict[\"a\"] = value[0:i]\n",
    "            if nums_b != 0:\n",
    "                b_len = (len_value-nums_a*i)//nums_b\n",
    "                a_dict[\"b\"] = value[i*first_b_index:i*first_b_index+b_len]\n",
    "            else:\n",
    "                a_dict[\"b\"] = \"\"\n",
    "            temp = \"\"\n",
    "            print(a_dict[\"a\"])\n",
    "            print(a_dict[\"b\"])\n",
    "            for j in pattern:\n",
    "                temp += a_dict[j]\n",
    "            if temp == value and a_dict[\"a\"]!=a_dict[\"b\"]:\n",
    "                return True\n",
    "        return False\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        if pattern[0] == 'a':\n",
    "            rega = '\\\\1'\n",
    "            regb = '\\\\2'\n",
    "        else:\n",
    "            rega = '\\\\2'\n",
    "            regb = '\\\\1'\n",
    "        \n",
    "        p = pattern.replace('a', '(\\\\w*)', 1).replace('b', '(\\\\w*)', 1)\n",
    "        p = p.replace('a', rega).replace('b', regb)\n",
    "        p = '^'+p+'$'\n",
    "        \n",
    "        res = re.match(p, value)\n",
    "        if res:\n",
    "            print(res.groups())\n",
    "            if len(res.groups()) == 1:\n",
    "                return True \n",
    "            elif len(res.groups()) == 2:\n",
    "                if res.groups()[0] != res.groups()[1]:\n",
    "                    return True \n",
    "        return False \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        n = len(value)\n",
    "        ma,mb = pattern.count('a'),pattern.count('b')\n",
    "        if n==0:\n",
    "            if ma*mb==0:return True\n",
    "            else:return False\n",
    "        if ma==1 or mb==1:return True\n",
    "        if ma==0 and mb==0:return False\n",
    "        if ma<mb:\n",
    "            pattern = pattern.replace('a','c').replace('b','a').replace('c','b')\n",
    "            ma,mb = mb,ma\n",
    "        # print(pattern,ma,mb)\n",
    "        for x in range(n//ma+1):\n",
    "            dicts = {}\n",
    "            if mb!=0:\n",
    "                y = (n-ma*x)/mb\n",
    "                if y!=int(y):continue\n",
    "                else:y=int(y)\n",
    "            sta = 0\n",
    "            for i in range(ma+mb):\n",
    "                if pattern[i]=='a':\n",
    "                    dicts[pattern[i]] = value[sta:sta+x]\n",
    "                    sta += x\n",
    "                else:\n",
    "                    dicts[pattern[i]] = value[sta:sta+y]\n",
    "                    sta+=y\n",
    "                if mb==0 or len(dicts)==2:break\n",
    "            if mb!=0 and dicts['a']==dicts['b']:continue\n",
    "            # print(dicts)\n",
    "            acc = ''\n",
    "            for c in pattern:\n",
    "                acc+=dicts[c]\n",
    "            # print(acc)\n",
    "            if acc==value:\n",
    "                return True\n",
    "        return False\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "\"\"\"\n",
    "\"a\"\n",
    "\"\"\n",
    "\"\"\n",
    "\"\"\n",
    "\"\"\n",
    "\"dogcatcatdog\"\n",
    "\n",
    "\"abba\"\n",
    "\"dogcatcatdog\"\n",
    "\"abba\"\n",
    "\"dogcatcatfish\"\n",
    "\"aaaa\"\n",
    "\"dogcatcatdog\"\n",
    "\"abba\"\n",
    "\"dogdogdogdog\"\n",
    "\n",
    "0 <= len(pattern) <= 1000\n",
    "0 <= len(value) <= 1000\n",
    "pattern only contains \"a\" and \"b\", value only contains lowercase letters.\n",
    "\n",
    "Math, String, Backtracking, Enumeration\n",
    "\"\"\"\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        ac, bc, vsize = 0, 0, len(value)\n",
    "        for ch in pattern:\n",
    "            ac += ch == 'a'\n",
    "            bc += ch == 'b'\n",
    "        if not value: return not ac or not bc\n",
    "        _al, _bl = 0, 0\n",
    "        if ac: _al = vsize//ac\n",
    "        if bc: _bl = vsize//bc\n",
    "\n",
    "        for al in range(_al+1):\n",
    "            for bl in range(_bl+1):\n",
    "                if al*ac + bl*bc != vsize: continue\n",
    "                astr = ''; bstr = ''\n",
    "                w = 0\n",
    "                for ch in pattern:\n",
    "                    if ch == 'a':\n",
    "                        if not astr:\n",
    "                            astr = value[w:w+al]\n",
    "                        else:\n",
    "                            if value[w:w+al] != astr: break\n",
    "                        w += al\n",
    "                    else:\n",
    "                        if not bstr:\n",
    "                            bstr = value[w:w+bl]\n",
    "                        else:\n",
    "                            if value[w:w+bl] != bstr: break\n",
    "                        w += bl\n",
    "\n",
    "                if w == vsize and astr != bstr: return True\n",
    "        return False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        # 边界情况处理\n",
    "        if not pattern: return not value\n",
    "        if len(pattern) == 1: return True\n",
    "\n",
    "        # 构造正则表达式：重点是正则表达式的“后向引用”\n",
    "        rega, regb = ('\\\\1', '\\\\2') if pattern[0] == 'a' else ('\\\\2', '\\\\1')\n",
    "        p = pattern.replace('a', '(\\\\w*)', 1).replace('b', '(\\\\w*)', 1).replace('a', rega).replace('b', regb)\n",
    "        p = '^' + p + '$'\n",
    "        m = re.match(p, value)\n",
    "        if m:          \n",
    "            # 匹配到 && (模式长度为1 || 模式长度为2 && 两个模式不相同)\n",
    "            if len(set(m.groups()))==len(m.groups()):\n",
    "                return True\n",
    "            else:\n",
    "                return False\n",
    "        else:\n",
    "            return False\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "\n",
    "        pattern_len = len(pattern)\n",
    "        if pattern_len == 1:\n",
    "            return True\n",
    "        if not value:\n",
    "            return False\n",
    "        value_len = len(value)\n",
    "        counter = Counter(pattern)\n",
    "        # a_len*counter_a + b_len*counter_b = pattern_len\n",
    "        # print(counter)\n",
    "        counter_a = counter.get(\"a\")\n",
    "        counter_b = counter.get(\"b\")\n",
    "        # print(counter_a, counter_b)\n",
    "        if not (counter_a and counter_b):\n",
    "            p = counter_a or counter_b\n",
    "            div, mod = divmod(value_len, p)\n",
    "            if mod:\n",
    "                return False\n",
    "            cmp = value[:div]\n",
    "            start = 0\n",
    "            for end in range(div, value_len+1, div):\n",
    "                if cmp != value[start:end]:\n",
    "                    return False\n",
    "                start= end\n",
    "            return True\n",
    "        t_max = value_len//counter_a\n",
    "        for a_len in range(t_max+1):\n",
    "        \n",
    "            b_len, mod = divmod((value_len - (a_len*counter_a)), counter_b)\n",
    "            # print(a_len,b_len)\n",
    "            if b_len<0:\n",
    "                return False\n",
    "            if mod:\n",
    "                continue\n",
    "            a_lindex_list  =[]\n",
    "            b_index_list = []\n",
    "            start =end= 0\n",
    "            for v in pattern:\n",
    "                if v == \"a\":\n",
    "                    end = start+a_len\n",
    "                    a_lindex_list.append((start, end))\n",
    "                else:\n",
    "                    end = start+b_len\n",
    "                    b_index_list.append((start, end))\n",
    "                start = end\n",
    "            a_cmp = value[a_lindex_list[0][0]:a_lindex_list[0][1]]\n",
    "            b_cmp = value[b_index_list[0][0]:b_index_list[0][1]]\n",
    "            if a_cmp == b_cmp:\n",
    "                continue\n",
    "            match = True\n",
    "            for a_x,a_y in a_lindex_list:\n",
    "                if value[a_x:a_y] != a_cmp:\n",
    "                    match = False\n",
    "                    break\n",
    "            if not match:\n",
    "                continue\n",
    "            for b_x,b_y in b_index_list:\n",
    "                if value[b_x:b_y] != b_cmp:\n",
    "                    match = False\n",
    "                    break\n",
    "            if not match:\n",
    "                continue\n",
    "            return True\n",
    "        return False\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        v_len = len(value)\n",
    "        num_a = len([i for i in pattern if i == 'a'])\n",
    "        num_b = len(pattern)-num_a\n",
    "        print(v_len)\n",
    "        print(num_b)\n",
    "        pair=[]\n",
    "        \n",
    "        if num_a == 0:\n",
    "            if v_len % num_b != 0:\n",
    "                return False\n",
    "            else:\n",
    "                pair.append((0,v_len//num_b))\n",
    "            \n",
    "        if num_b == 0:\n",
    "            if v_len % num_a != 0:\n",
    "                return False\n",
    "            else:\n",
    "                pair.append((v_len//num_a,0))\n",
    "        \n",
    "        if num_a != 0 and num_b != 0:\n",
    "            for i in range(0,v_len+1):\n",
    "                if num_a * i > v_len:\n",
    "                    break;\n",
    "                c = v_len - num_a * i\n",
    "                if c % num_b == 0:\n",
    "                    pair.append((i,c//num_b))\n",
    "            \n",
    "        if len(pair) == 0:\n",
    "            return False\n",
    " \n",
    "        result = True\n",
    "        for i,j in pair:\n",
    "            pos = 0\n",
    "            f_a = None\n",
    "            f_b = None\n",
    "            res = True\n",
    "            for x in pattern:\n",
    "                if x == 'a':\n",
    "                    a = value[pos:pos+i]\n",
    "                    pos = pos+i\n",
    "                    if f_a is None:\n",
    "                        f_a = a\n",
    "                    elif f_a != a:\n",
    "                        res = False\n",
    "                        break\n",
    "                    \n",
    "                if x == 'b':\n",
    "                    b = value[pos:pos+j]\n",
    "                    pos = pos+j\n",
    "                    if f_b is None:\n",
    "                        f_b = b\n",
    "                    elif f_b != b:\n",
    "                        res = False\n",
    "                        break\n",
    "                        \n",
    "        \n",
    "            if f_a == f_b:\n",
    "                res = False\n",
    "               \n",
    "            result = res\n",
    "            if res:\n",
    "                break\n",
    "        return  result      "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        # 题目本身比较容易理解，但细节太多了，给出官方的思路————枚举\n",
    "        count_a = sum(1 for ch in pattern if ch == \"a\")\n",
    "        count_b = len(pattern) - count_a\n",
    "        if count_a < count_b:\n",
    "            count_a,count_b = count_b,count_a\n",
    "            pattern = \"\".join(\"a\" if ch == \"b\" else \"b\" for ch in pattern)\n",
    "\n",
    "        if not value:\n",
    "            return count_b == 0\n",
    "        if not pattern:\n",
    "            return False\n",
    "\n",
    "        for len_a in range(len(value) // count_a + 1):\n",
    "            rest = len(value) - count_a * len_a\n",
    "            if (count_b == 0 and rest == 0) or (count_b != 0 and rest % count_b == 0):\n",
    "                len_b = 0 if count_b == 0 else rest // count_b\n",
    "                pos,correct = 0,True\n",
    "                value_a,value_b = None,None\n",
    "                for ch in pattern:\n",
    "                    if ch == \"a\":\n",
    "                        sub = value[pos:pos + len_a]\n",
    "                        if not value_a:\n",
    "                            value_a = sub\n",
    "                        elif value_a != sub:\n",
    "                            correct = False\n",
    "                            break\n",
    "                        pos += len_a\n",
    "                    else:\n",
    "                        sub = value[pos:pos + len_b]\n",
    "                        if not value_b:\n",
    "                            value_b = sub\n",
    "                        elif value_b != sub:\n",
    "                            correct = False\n",
    "                            break\n",
    "                        pos += len_b\n",
    "                if correct and value_a != value_b:\n",
    "                    return True\n",
    "        return False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        if not pattern:return not value\n",
    "        if len(pattern)==1:return True\n",
    "        a,b = ('\\\\1','\\\\2') if pattern[0]=='a' else ('\\\\2','\\\\1')\n",
    "        p = pattern.replace('a','(\\\\w*)',1).replace('b','(\\\\w*)',1).replace('a',a).replace('b',b)\n",
    "        res = re.match('^'+p+'$',value)\n",
    "        return bool(res and (len(res.groups())==1 or res.groups()[0]!=res.groups()[1]))\n",
    "\n",
    "\n",
    "        # n = len(value)\n",
    "        # ma,mb = pattern.count('a'),pattern.count('b')\n",
    "        # if n==0:\n",
    "        #     if ma*mb==0:return True\n",
    "        #     else:return False\n",
    "        # if ma==1 or mb==1:return True\n",
    "        # if ma==0 and mb==0:return False\n",
    "        # if ma<mb:\n",
    "        #     pattern = pattern.replace('a','c').replace('b','a').replace('c','b')\n",
    "        #     ma,mb = mb,ma\n",
    "        # for x in range(n//ma+1):\n",
    "        #     dicts = {}\n",
    "        #     if mb!=0:\n",
    "        #         y = (n-ma*x)/mb\n",
    "        #         if y!=int(y):continue\n",
    "        #         else:y=int(y)\n",
    "        #     sta = 0\n",
    "        #     for i in range(ma+mb):\n",
    "        #         if pattern[i]=='a':\n",
    "        #             dicts[pattern[i]] = value[sta:sta+x]\n",
    "        #             sta += x\n",
    "        #         else:\n",
    "        #             dicts[pattern[i]] = value[sta:sta+y]\n",
    "        #             sta+=y\n",
    "        #         if mb==0 or len(dicts)==2:break\n",
    "        #     if mb!=0 and dicts['a']==dicts['b']:continue\n",
    "        #     acc = ''\n",
    "        #     for c in pattern:\n",
    "        #         acc+=dicts[c]\n",
    "        #     if acc==value:\n",
    "        #         return True\n",
    "        # return False\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        count_a = sum(1 for ch in pattern if ch == 'a')\n",
    "        count_b = len(pattern) - count_a\n",
    "        if count_a < count_b:\n",
    "            count_a, count_b = count_b, count_a\n",
    "            pattern = ''.join('a' if ch == 'b' else 'b' for ch in pattern)\n",
    "        \n",
    "        if not value:\n",
    "            return count_b == 0\n",
    "        if not pattern:\n",
    "            return False\n",
    "        \n",
    "        for len_a in range(len(value) // count_a + 1):\n",
    "            rest = len(value) - count_a * len_a\n",
    "            if (count_b == 0 and rest == 0) or (count_b != 0 and rest % count_b == 0):\n",
    "                len_b = 0 if count_b == 0 else rest // count_b\n",
    "                pos, correct = 0, True\n",
    "                value_a, value_b = None, None\n",
    "                for ch in pattern:\n",
    "                    if ch == 'a':\n",
    "                        sub = value[pos:pos+len_a]\n",
    "                        if not value_a:\n",
    "                            value_a = sub\n",
    "                        elif value_a != sub:\n",
    "                            correct = False\n",
    "                            break\n",
    "                        pos += len_a\n",
    "                    else:\n",
    "                        sub = value[pos:pos+len_b]\n",
    "                        if not value_b:\n",
    "                            value_b = sub\n",
    "                        elif value_b != sub:\n",
    "                            correct = False\n",
    "                            break\n",
    "                        pos += len_b\n",
    "                if correct and value_a != value_b:\n",
    "                    return True\n",
    "        \n",
    "        return False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        # 边界情况处理\n",
    "        if not pattern: return not value\n",
    "        if len(pattern) == 1: return True\n",
    "\n",
    "        # 构造正则表达式：重点是正则表达式的“后向引用”\n",
    "        rega, regb = ('\\\\1', '\\\\2') if pattern[0] == 'a' else ('\\\\2', '\\\\1')\n",
    "        p = pattern.replace('a', '(\\\\w*)', 1).replace('b', '(\\\\w*)', 1).replace('a', rega).replace('b', regb)\n",
    "        p = '^' + p + '$'\n",
    "        m = re.match(p, value)\n",
    "\n",
    "        # 匹配到 && (模式长度为1 || 模式长度为2 && 两个模式不相同)\n",
    "        return bool(m and (len(m.groups()) == 1 or m.groups()[0] != m.groups()[1]))\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        ca=pattern.count('a')\n",
    "        cb=pattern.count('b')\n",
    "        if not value and ca*cb==0:\n",
    "            return True\n",
    "        if ca==0:\n",
    "            pattern='a'*len(pattern)\n",
    "            ca,cb=cb,ca\n",
    "        if ca>0:\n",
    "            idxa=pattern.index('a')\n",
    "        if cb>0:\n",
    "            idxb=pattern.index('b')\n",
    "        m=len(pattern)\n",
    "        n=len(value)\n",
    "        for i in range(n+1):\n",
    "            if i*ca>n:\n",
    "                break \n",
    "            if cb==0 and n!=i*ca:\n",
    "                continue\n",
    "            if cb!=0 and (n-i*ca)%cb!=0:\n",
    "                continue\n",
    "            if cb!=0:\n",
    "                j=(n-i*ca)//cb \n",
    "                pa=value[idxa*j:idxa*j+i]\n",
    "                pb=value[idxb*i:idxb*i+j]\n",
    "                print(pa,pb)\n",
    "\n",
    "                if pa==pb:\n",
    "                    continue\n",
    "                s=[]\n",
    "                for x in pattern:\n",
    "                    if x==\"a\":\n",
    "                        s.append(pa)\n",
    "                    else:\n",
    "                        s.append(pb)\n",
    "                s=\"\".join(s)\n",
    "            else:\n",
    "                pa=value[:i]\n",
    "                s=pattern.replace('a',pa)\n",
    "\n",
    "            if s==value:\n",
    "                return True\n",
    "        return False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "from collections import Counter\n",
    "class Solution:\n",
    "    def check(self,pattern: str, value: str ,lenP: dict)->bool:\n",
    "        \"\"\"\n",
    "        :param pattern , value: Be same as patternMatching()\n",
    "        :param lenP: lenP={'a':la ,'b':lb}\n",
    "        :return: bool\n",
    "        \"\"\"\n",
    "        strD={}\n",
    "        strS=set()\n",
    "        si=0\n",
    "        for ch in pattern:\n",
    "            _str=value[si:si+lenP[ch]]\n",
    "            if ch not in strD:\n",
    "                if _str not in strS: # 但需注意\"a\"和\"b\"不能同时表示相同的字符串\n",
    "                    strD[ch]=_str\n",
    "                    strS.add(_str)\n",
    "                else: return False\n",
    "            elif _str!=strD[ch]:\n",
    "                return False\n",
    "            si += lenP[ch]\n",
    "        return True\n",
    "\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        if \"\"==pattern: return \"\"==value    # ①\n",
    "        Cab=Counter(pattern)    #计数pattern中每个元素的出现次数\n",
    "        na,nb = Cab['a'],Cab['b']   #求得na,nb\n",
    "        if 0==na:   # 由①: na和nb 不可能同时为0.\n",
    "            if 0==len(value)%nb:\n",
    "                return self.check(pattern,value,{'b':len(value)//nb,})\n",
    "        elif 0==nb: #零值特别处理\n",
    "            if 0==len(value)%na:\n",
    "                return self.check(pattern,value,{'a':len(value)//na,})\n",
    "        else:\n",
    "            for la in range(len(value)+1):\n",
    "                sb = len(value)-na*la # sb= nb*lb\n",
    "                if sb <0:return False\n",
    "                if sb%nb ==0:\n",
    "                    lb=sb//nb\n",
    "                    if self.check(pattern,value,{'a':la,'b':lb}):\n",
    "                        return True #有解\n",
    "        return False\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        # 按pattern分配a、b长度：先求数量，再搜索不定方程整数解\n",
    "        np = len(pattern)\n",
    "        lv = len(value)\n",
    "        if lv == 0 and np == 1:\n",
    "            return True\n",
    "        na = 0\n",
    "        nb = 0\n",
    "        la_lbs = []  # a、b可能长度对\n",
    "        for x in pattern:\n",
    "            if x == \"a\":\n",
    "                na += 1\n",
    "            else:\n",
    "                nb += 1\n",
    "        # 优化：保证a出现的次数比b多，不满足时交换\n",
    "        if na < nb:\n",
    "            na, nb = nb, na\n",
    "            pattern = ''.join('a' if ch == 'b' else 'b' for ch in pattern)\n",
    "\n",
    "        if na == 0:\n",
    "            if lv % nb == 0:\n",
    "                la_lbs.append([0, lv // nb])\n",
    "        else:\n",
    "            for la in range(lv // na + 1):\n",
    "                if nb == 0:\n",
    "                    if lv == la * na:  # 没有b且a长度满足要求\n",
    "                        la_lbs.append([la, 0])\n",
    "                elif (lv - la * na) % nb == 0:\n",
    "                    la_lbs.append([la, (lv - la * na) // nb])\n",
    "        if len(la_lbs) == 0:  # pattern长度无法匹配\n",
    "            return False\n",
    "\n",
    "        #  对每个可能的长度对，找到a、b对应位置的字符串，遍历并匹配 \n",
    "        for la_lb in la_lbs:\n",
    "            start_idx = 0  # 当前匹配子串索引\n",
    "            a, b = \"\", \"\"\n",
    "            la, lb = la_lb[0], la_lb[1]\n",
    "            flag = False\n",
    "            for x in pattern:\n",
    "                if x == \"a\":\n",
    "                    cur_a = value[start_idx:start_idx+la]\n",
    "                    start_idx = start_idx + la\n",
    "                    # print(cur_a)\n",
    "                    # print(a)\n",
    "                    if not a:\n",
    "                       a = cur_a # 第一个a匹配的子串\n",
    "                       flag = True\n",
    "                    elif cur_a != a:  # 不同的a对应不同子串，匹配失败\n",
    "                        flag = False\n",
    "                        break\n",
    "                    else:\n",
    "                        flag = True\n",
    "                elif x == \"b\":\n",
    "                    cur_b = value[start_idx:start_idx+lb]\n",
    "                    start_idx = start_idx + lb\n",
    "                    if not b:\n",
    "                        b = cur_b # 第一个a匹配的子串\n",
    "                        flag = True\n",
    "                    elif cur_b != b:  # 不同的a对应不同子串，匹配失败\n",
    "                        flag = False\n",
    "                        break\n",
    "                    else:\n",
    "                        flag = True\n",
    "            if flag and a != b:  # 如果完全匹配且ab不同则返回True\n",
    "                return True\n",
    "        return False  # 全部长度均失败\n",
    "\n",
    "            \n",
    "\n",
    "\n",
    "\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        from collections import Counter\n",
    "        import itertools\n",
    "        if pattern in (\"a\", \"b\") or pattern == value or (pattern==\"ab\" and value!=\"\"):\n",
    "            return True\n",
    "        if not pattern:\n",
    "            return False\n",
    "        cache = Counter(pattern)\n",
    "        n = len(value)\n",
    "\n",
    "        if cache[\"a\"] == 0:\n",
    "            if n%cache[\"b\"]:\n",
    "                return False\n",
    "            length = n // cache[\"b\"]\n",
    "            seq = [value[i:i+length] for i in range(0, n, length)]\n",
    "            return all(i==seq[0] for i in seq)\n",
    "        \n",
    "        if cache[\"b\"] == 0:\n",
    "            if n%cache[\"a\"]:\n",
    "                return False\n",
    "            length = n // cache[\"a\"]\n",
    "            seq = [value[i:i+length] for i in range(0, n, length)]\n",
    "            return all(i==seq[0] for i in seq)\n",
    "        \n",
    "        if not value:\n",
    "            return False\n",
    "        \n",
    "        for i in range(n//cache[\"a\"]+1):\n",
    "            if (n - cache[\"a\"]*i)%cache[\"b\"] == 0:\n",
    "                j = (n - cache[\"a\"]*i)//cache[\"b\"]\n",
    "                seq_a = []\n",
    "                seq_b = []\n",
    "                ptr = 0\n",
    "                for c in pattern:\n",
    "                    if c == \"a\":\n",
    "                        seq_a.append(value[ptr:ptr+i])\n",
    "                        ptr += i\n",
    "                    else:\n",
    "                        seq_b.append(value[ptr:ptr+j])\n",
    "                        ptr += j\n",
    "                if all(i == seq_a[0] for i in seq_a) and all(i == seq_b[0] for i in seq_b) and seq_a[0] != seq_b[0]:\n",
    "                    return True\n",
    "        return False\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def patternMatching(self, pattern: str, value: str) -> bool:\n",
    "        count_a = sum(1 for ch in pattern if ch == 'a')\n",
    "        count_b = len(pattern) - count_a\n",
    "        if count_a < count_b:\n",
    "            count_a, count_b = count_b, count_a\n",
    "            pattern = ''.join('a' if ch == 'b' else 'b' for ch in pattern)\n",
    "        \n",
    "        if not value:\n",
    "            return count_b == 0\n",
    "        if not pattern:\n",
    "            return False\n",
    "        \n",
    "        for len_a in range(len(value) // count_a + 1):\n",
    "            rest = len(value) - count_a * len_a\n",
    "            if (count_b == 0 and rest == 0) or (count_b != 0 and rest % count_b == 0):\n",
    "                len_b = 0 if count_b == 0 else rest // count_b\n",
    "                pos, correct = 0, True\n",
    "                value_a, value_b = None, None\n",
    "                for ch in pattern:\n",
    "                    if ch == 'a':\n",
    "                        sub = value[pos:pos+len_a]\n",
    "                        if not value_a:\n",
    "                            value_a = sub\n",
    "                        elif value_a != sub:\n",
    "                            correct = False\n",
    "                            break\n",
    "                        pos += len_a\n",
    "                    else:\n",
    "                        sub = value[pos:pos+len_b]\n",
    "                        if not value_b:\n",
    "                            value_b = sub\n",
    "                        elif value_b != sub:\n",
    "                            correct = False\n",
    "                            break\n",
    "                        pos += len_b\n",
    "                if correct and value_a != value_b:\n",
    "                    return True\n",
    "        \n",
    "        return False\n",
    "\n",
    "# 作者：力扣官方题解\n",
    "# 链接：https://leetcode.cn/problems/pattern-matching-lcci/solutions/298105/mo-shi-pi-pei-by-leetcode-solution/\n",
    "# 来源：力扣（LeetCode）\n",
    "# 著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 2
}
